<?php
namespace app\api\controller\damp;
/***
 *      ┌─┐       ┌─┐
 *   ┌──┘ ┴───────┘ ┴──┐
 *   │                 │
 *   │       ───       │
 *   │  ─┬┘       └┬─  │
 *   │                 │
 *   │       ─┴─       │
 *   │                 │
 *   └───┐         ┌───┘
 *       │         │    神兽保佑代码没有bug
 *       │         │
 *       │         │
 *       │         └──────────────┐
 *       │                        │
 *       │                        ├─┐
 *       │                        ┌─┘
 *       │                        │
 *       └─┐  ┐  ┌───────┬──┐  ┌──┘
 *         │ ─┤ ─┤       │ ─┤ ─┤
 *         └──┴──┘       └──┴──┘
 *              购物车控制器
 */
use think\facade\Db;
use think\Request;
use app\BaseController;
use app\common\controller\ApiController;
use think\App;

class Cart extends ApiController
{

    public function initialize()
    {
        parent::initialize();
        $this->cart = app('app\common\model\mall\ItemCart');
        $this->item = app('app\common\model\mall\Item');
        $this->store = app('app\common\model\mall\Store');
        $this->itemSku = app('app\common\model\mall\ItemSku');
    }

    /**
     * 添加购物车
     */
    public function add_cart(Request $request)
    {

        $params = $request->param();
        try {
            $this->validate($params , [
                'item_id|商品id' => 'require' ,
                'sku_id|规格' => 'require' ,
                'number|数量' => 'require' ,
            ]);
            //检查商品的状态
            $store_id = $this->item->where(['id' => $params['item_id'] , 'status' => 1])->value('store_id');

            if (!$store_id) throw new \Exception('商品状态异常');


            //查询库存
            $sku_number = $this->itemSku->where('id' , $params['sku_id'])->value('inventory');
            if ($sku_number < $params['number'])
                throw new \Exception('商品库存不足');

            //商品数据入购物车
            $cartData = [
                'user_id' => $request->user_id ,
                'item_id' => $params['item_id'] ,
                'sku_id' => $params['sku_id'] ,
                'store_id' => $store_id ,
            ];

            //判断购物车是否存在当前商品，存在则数量累加
            $cart_info = $this->cart->where($cartData)->find();
            if ($cart_info['number']) {
                if ($params['number'] + $cart_info['number'] > $sku_number)
                    throw new \Exception('商品库存不足');
                else
                    $cart_info->inc('number' , $params['number'])->update();
            } else {
                $cartData['number'] = $params['number'];
                $this->cart->save($cartData);
            }

            return json(['code' => 200 , 'msg' => '添加购物车成功']);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }

    }

    /**
     * 编辑购物车
     * @param Request $request
     */
    public function edit_cart(Request $request)
    {
        $params = $request->param();
        try {

            if (empty( $params['id'] )) throw new \Exception('购物车id不能为空');

            $cart_info = $this->cart->find($params['id']);

            $sku_number = $this->itemSku->where('id' , $cart_info->sku_id)->value('inventory');

            if ($sku_number < $params['number']) throw new \Exception('库存不足');

            $cart_info->save($params);

            return json(['code' => 200 , 'msg' => '编辑购物车成功']);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 删除购物车
     * @param Request $request
     * @return \think\response\Json
     */
    public function del_cart(Request $request)
    {
        $params = $request->param();
        try {
            if (empty( $params['ids'] )) throw new \Exception('购物车id不能为空');

            $lists = $this->cart->whereIn('id' , $params['ids'])->select();

            $lists && $lists->delete();

            return json(['code' => 200 , 'msg' => '删除购物车成功']);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);
        }

    }


    /**
     * 购物车列表
     * @param Request $request
     */
    public function cart_list(Request $request){
        try {

            $store_id = $this->cart->column('store_id');
            $lists = $this->store->whereIn('id',$store_id)->field('id,name')->select()->toArray();

            foreach($lists as $k=>$v)
            {
                $lists[$k][] =$this->cart->where('user_id' , $request->user_id)
                    ->with(['item','sku'])
                    ->where('store_id',$v['id'])
                    ->select()->toArray();
            }
            return json(['code' => 200 , 'data' => ['data'=>$lists]]);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);
        }
    }
}